package cn.stylefeng.guns.modular.business.frequency.orderpick.controller;

import cn.stylefeng.guns.core.context.login.LoginContextHolder;
import cn.stylefeng.guns.core.pojo.page.AndaPageResult;
import cn.stylefeng.guns.core.pojo.response.ResponseData;
import cn.stylefeng.guns.modular.business.custom.enums.OrderStatusEnum;
import cn.stylefeng.guns.modular.business.custom.enums.PickCarTypeEnum;
import cn.stylefeng.guns.modular.business.frequency.finance.service.FinanceService;
import cn.stylefeng.guns.modular.business.frequency.ordercarverify.entity.OrderCarVerify;
import cn.stylefeng.guns.modular.business.frequency.ordercarverify.service.OrderCarVerifyService;
import cn.stylefeng.guns.modular.business.frequency.orderpick.entity.OrderPick;
import cn.stylefeng.guns.modular.business.frequency.orderpick.model.param.PickCarExcludeDTO;
import cn.stylefeng.guns.modular.business.frequency.orderpick.model.param.PickDTO;
import cn.stylefeng.guns.modular.business.frequency.orderpick.model.result.PkgOrderPick;
import cn.stylefeng.guns.modular.business.frequency.orderpick.service.OrderPickService;
import cn.stylefeng.guns.modular.business.frequency.ordersub.model.result.PkgPick;
import cn.stylefeng.guns.modular.business.frequency.siterelation.entity.SiteRelation;
import cn.stylefeng.guns.modular.business.frequency.siterelation.service.SiteRelationService;
import cn.stylefeng.guns.modular.business.frequency.syssite.mapper.SysSiteMapper;
import cn.stylefeng.guns.modular.business.util.BusinessUtil;
import cn.stylefeng.guns.sys.modular.role.RoleConstant;
import cn.stylefeng.guns.sys.modular.user.service.SysUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Author jzy
 * @Date 2020/10/10 0010
 **/
@Api(tags = "订单模块：提车管理")
@RestController
@RequestMapping("/api/pick")
public class OrderPickController {

    @Resource
    private OrderPickService pickCarService;
    @Resource
    private FinanceService financeService;
    @Resource
    private SysSiteMapper siteMapper;
    @Autowired
    private OrderCarVerifyService orderCarVerifyService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private BusinessUtil businessUtil;

    @ApiOperation(value = "提车待处理列表")
    @GetMapping("/wait")
    @PreAuthorize("@el.check('pickcar:list')")
    public ResponseData getWaitDealOrderList(PickDTO orderDTO) {
        if (StringUtils.isBlank(orderDTO.getColumn())) {
            orderDTO.setColumn("os.create_time");
        }
        // 数据权限
        List<Long> empByOrgList = businessUtil.getEmpByOrgList();
        orderDTO.setDataList(empByOrgList);
        // 添加网点部角色数据范围
        getPickCarOrderQueryParam(orderDTO);

        Page<PkgOrderPick> list = pickCarService.getWaitDealOrderList(orderDTO);
        if (list != null && list.getRecords() != null && list.getRecords().size() > 0) {
            for (PkgOrderPick pick : list.getRecords()) {
                // 处理提车状态、验车状态
                dualPickAndVerifyStatus(pick);
            }
        }
        return ResponseData.andaSuccess(new AndaPageResult<>().AndaPageResult(list, orderDTO));
    }


    @Autowired
    private SiteRelationService siteRelationService;

    private void getPickCarOrderQueryParam(PickDTO orderDTO) {
        List<String> roleCodeList = sysUserService.getRoleCodeListByUserId(LoginContextHolder.me().getSysLoginUserId());
        //网点部可以看到自己服务城市的订单，即订单的出发地在自己网点的服务城市内，还有自己创建的订单，所以这里分配全部数据权限
        if (roleCodeList.contains(RoleConstant.网点部角色)) {
            SiteRelation siteRelation = siteRelationService.getOne(new LambdaQueryWrapper<SiteRelation>().eq(SiteRelation::getUserId, LoginContextHolder.me().getSysLoginUserId()));
            if (siteRelation != null && siteRelation.getSiteId() != null) {
                List<String> chargeCityList = siteMapper.getServiceCodes(siteRelation.getSiteId().toString());
                orderDTO.setStartCodeList(chargeCityList);
                orderDTO.setDispatcherId(LoginContextHolder.me().getSysLoginUserId().toString());
            }
            if (orderDTO.getStartCodeList() == null) {
                orderDTO.setStartCodeList(new ArrayList<>());
            }
            orderDTO.getStartCodeList().add("-1");
        }
    }

    @ApiOperation(value = "提车待处理列表")
    @GetMapping("/waitDetail")
    @PreAuthorize("@el.check('pickcar:list')")
    public ResponseData getWaitDealOrderDetailList(PickDTO orderDTO) {

        PkgOrderPick pkgOrderPick = pickCarService.getWaitDealOrderDetailList(orderDTO);
        // 处理提车状态、验车状态
        dualPickAndVerifyStatus(pkgOrderPick);

        return ResponseData.andaSuccess(pkgOrderPick);
    }

    @ApiOperation(value = "提车待处理出发地目的地筛选列表")
    @GetMapping("/sd-codes")
    public ResponseData getStartCodeAndDestinationCode() {
        PickDTO orderDTO = new PickDTO();
        List<Long> empByOrgList = businessUtil.getEmpByOrgList();
        orderDTO.setDataList(empByOrgList);
        Map<String, List<String>> map = pickCarService.getStartCodeAndDestinationCode(orderDTO);
        return ResponseData.andaSuccess(map);
    }


    /**
     * 提车记录列表  已完成提车列表
     */
    @ApiOperation(value = "已完成提车列表")
    @GetMapping("/finish")
    @PreAuthorize("@el.check('pickcar:list')")
    public ResponseData getFinishOrderList(PickDTO orderDTO) {
        // 排序
        if (StringUtils.isBlank(orderDTO.getColumn())) {
            orderDTO.setColumn("os.create_time");
        }
        List<Long> empByOrgList = businessUtil.getEmpByOrgList();
        orderDTO.setDataList(empByOrgList);
        Page<PkgOrderPick> list = pickCarService.getFinishOrderList(orderDTO);
        return ResponseData.andaSuccess(new AndaPageResult<>().AndaPageResult(list, orderDTO));
    }


    @ApiOperation(value = "添加待提车弹框筛选")
    @GetMapping("/wait-exclude")
    @PreAuthorize("@el.check('pickcar:list')")
    public ResponseData getWaitPickExclude(PickCarExcludeDTO pickCarExcludeDTO) {
        // 数据权限
        List<Long> empByOrgList = businessUtil.getEmpByOrgList();
        pickCarExcludeDTO.setDataList(empByOrgList);
        List<PkgOrderPick> list = pickCarService.getWaitPickExcludeList(pickCarExcludeDTO);
        return ResponseData.andaSuccess(list);
    }

    //@NoRepeatSubmit
    @ApiOperation(value = "批量指派提车")
    @PostMapping("/multi-pick")
    @PreAuthorize("@el.check('pickcar:add')")
    public ResponseData assignPick(@Validated @RequestBody OrderPick orderPick) {
        StringBuilder errorMsg = new StringBuilder();
     /*   boolean hasAssignDriver = BaseUtils.hasAssignDriver(orderPick.getDriverId(), orderPick.getDriverName()
                , orderPick.getDriverPhone(), orderPick.getDriverCardNumber(), orderPick.getLicensePlateNumber());*/
        if (!pickCarService.checkMultiAssign(orderPick, errorMsg)) {
            return ResponseData.andaError(errorMsg.toString());
        }
        pickCarService.multiAssign(orderPick);
        return ResponseData.andaSuccess("");

    }

    @ApiOperation(value = "回退提车")
    @GetMapping("/return-multi-pick/{orderId}")
    @PreAuthorize("@el.check('pickcar:edit')")
    public ResponseData returnAssignPick(@PathVariable Long orderId) {
        pickCarService.returnMultiAssign(orderId);
        return ResponseData.andaSuccess();

    }


    @ApiOperation(value = "提车信息详情")
    @GetMapping("/detail/{orderId}")
    public ResponseData getPickCarDetail(@PathVariable Long orderId) {
        PkgPick pick = pickCarService.getPickCarDetail(orderId);
        return ResponseData.andaSuccess(pick);
    }


    @ApiOperation(value = "指派司机编辑")
    @PutMapping
    public ResponseData updateAssignPick(@Validated @RequestBody OrderPick orderPick) {
        StringBuilder errorMsg = new StringBuilder();
        if (!pickCarService.checkAssignUpdate(orderPick, errorMsg)) {
            return ResponseData.andaError(errorMsg.toString());
        }
        if (orderPick.getOrderCarVerify() != null) {
            orderCarVerifyService.updateVerify(orderPick.getOrderCarVerify());
        }
        pickCarService.updateAssign(orderPick);
        // finance表状态修改
        financeService.changeFinanceStatus(orderPick.getOrderId());
        return ResponseData.andaSuccess();
    }

    @ApiOperation(value = "验车信息查看")
    @GetMapping("/verify/{orderId}")
    public ResponseData viewVerify(@PathVariable Long orderId) {
        OrderCarVerify ocv = pickCarService.getOrderCarVerifyByOrderId(orderId);
        return ResponseData.andaSuccess(ocv);
    }


    @ApiOperation(value = "提车入库")
    @PostMapping("/stock/{orderId}")
    @PreAuthorize("@el.check('stockcar:add')")
    public ResponseData pickCarStock(@PathVariable Long orderId) {
        pickCarService.pickCarStock(orderId);
        return ResponseData.andaSuccess();
    }


    @ApiOperation(value = "免费提短")
    @PostMapping("/pick-free/{orderId}")
    @PreAuthorize("@el.check('pickcar:add')")
    public ResponseData orderPickFree(@PathVariable Long orderId) {
        StringBuilder errorMsg = new StringBuilder();
        if (!pickCarService.checkPickFree(orderId, errorMsg)) {
            return ResponseData.andaError(errorMsg.toString());
        }
        pickCarService.orderPickFree(orderId);
        return ResponseData.andaSuccess();
    }


    //@NoRepeatSubmit
    @ApiOperation(value = "批量免费提短")
    @PostMapping("/multi-pick-free")
    @PreAuthorize("@el.check('pickcar:add')")
    public ResponseData multiOrderPickFree(@RequestBody Long[] orderIds) {
        StringBuilder errorMsg = new StringBuilder();
        if (!pickCarService.checkMultiPickFree(orderIds, errorMsg)) {
            return ResponseData.andaError(errorMsg.toString());
        }
        for (Long id : orderIds) {
            pickCarService.orderPickFree(id);
        }
        return ResponseData.andaSuccess();
    }


    /**
     * 提车管理状态处理
     *
     * @param pick
     */
    private void dualPickAndVerifyStatus(PkgOrderPick pick) {
        // 提车状态：1.小板 2.人工 3.- 4.免费提短 5.已提短 6.已指派结算人
        if (pick.getPickType() == PickCarTypeEnum.ZI_SONG_WAND_DIAN.type) {
            pick.setPickCarStatus(3);
            pick.setDriverStatus(3);
        } else if (pick.getPickType() == PickCarTypeEnum.MIAN_FEE_TI_DUAN.type) {
            if (pick.getOrderStatus() == OrderStatusEnum.NEW_ORDER.status) {
                pick.setPickCarStatus(4);
            } else {
                pick.setPickCarStatus(5);
            }
            pick.setDriverStatus(3);
        } else {
            // 需要提车
            if (pick.getOrderStatus() == OrderStatusEnum.NEW_ORDER.status) {
                //提车方式
                if (pick.getPickType() == PickCarTypeEnum.XIAO_BAN_TI_CHE.type) {
                    pick.setPickCarStatus(1); // 1.小板提车
                } else {
                    pick.setPickCarStatus(2); // 2.人工提车
                }
            } else {
                pick.setPickCarStatus(6);
            }
            if (pick.getOrderStatus() == OrderStatusEnum.WAIT_ASSIGN_DRIVER.status) {
                pick.setDriverStatus(1);
            } else if (pick.getOrderStatus() == OrderStatusEnum.NEW_ORDER.status) {
                pick.setDriverStatus(3);
            } else {
                pick.setDriverStatus(2);
            }
        }
        // 验车状态： 1.- 2.待验车 3.已验车
        if (pick.getOrderStatus() == OrderStatusEnum.NEW_ORDER.status || pick.getOrderStatus() == OrderStatusEnum.WAIT_ASSIGN_DRIVER.status) {
            pick.setVerifyCarStatus(1);
        } else if (pick.getOrderStatus() == OrderStatusEnum.WAIT_PICK.status) {
            pick.setVerifyCarStatus(2);
        } else {
            pick.setVerifyCarStatus(3);
        }
        // 入库状态：1.待入库 2. -
        if (pick.getOrderStatus() == OrderStatusEnum.PICK_SIGNED.status) {
            pick.setStockStatus(1);
        } else {
            pick.setStockStatus(2);
        }
    }

}
